package cn.shoptnt.consumer.shop.trade.consumer;

import cn.shoptnt.client.system.SettingClient;
import cn.shoptnt.consumer.core.event.OrderStatusChangeEvent;
import cn.shoptnt.framework.trigger.Interface.TimeTrigger;
import cn.shoptnt.framework.util.JsonUtil;
import cn.shoptnt.model.base.SettingGroup;
import cn.shoptnt.model.base.message.OrderStatusChangeMsg;
import cn.shoptnt.model.base.rabbitmq.TimeExecute;
import cn.shoptnt.model.trade.order.dos.OrderDO;
import cn.shoptnt.model.trade.order.enums.OrderStatusEnum;
import cn.shoptnt.model.trade.order.enums.PaymentTypeEnum;
import cn.shoptnt.model.trade.order.vo.OrderSettingVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 新订单超时未付款自动取消
 *
 * @author zs
 * @version v7.3.0
 * @since 1.0.0
 * @date 2021/02/25
 */
@Component
public class OrderAutoCancelConsumer implements OrderStatusChangeEvent {

    @Autowired
    private SettingClient settingClient;

    @Autowired
    private TimeTrigger timeTrigger;

    @Override
    public void orderChange(OrderStatusChangeMsg orderMessage) {

        OrderDO orderDO = orderMessage.getOrderDO();

        //如果是新订单并且付款方式是在线支付,开启 自动取消订单 延时任务
        if (OrderStatusEnum.CONFIRM.equals(orderMessage.getNewStatus()) && PaymentTypeEnum.ONLINE.value().equals(orderDO.getPaymentType())) {

            //查询订单配置
            String json = this.settingClient.get(SettingGroup.TRADE);
            OrderSettingVO orderSetting = JsonUtil.jsonToObject(json, OrderSettingVO.class);

            //获取订单自动取消天数
            int day = orderSetting.getCancelOrderDay();
            //获取订单自动取消小时数
            int hour = orderSetting.getCancelOrderHour();
            //获取订单自动取消分钟数
            int minutes = orderSetting.getCancelOrderMinutes();
            //订单自动取消总分钟数 = 订单自动取消天数 * 24 * 60 + 订单自动取消小时数 * 60 + 订单自动取消分钟数
            int cancelMinutes = day * 24 * 60 + hour * 60 + minutes;

            //订单自动取消时间转为秒
            Long cancelOrderSecond = cancelMinutes * 60L;

            //延时任务执行时间 = 订单创建时间 + 自动取消时间
            Long triggerTime = orderDO.getCreateTime() + cancelOrderSecond;

            String uniqueKey = "{TIME_TRIGGER_" + orderDO.getSn();
            timeTrigger.add(TimeExecute.ORDER_AUTO_CANCEL, orderMessage, triggerTime, uniqueKey);

        }
    }
}
